// 我的活动页面
const auth = require('../../../utils/auth')
const activities = require('../../../api/activities')

Page({
  data: {
    loading: true,
    activities: [],
    allActivities: [], // 保存所有原始数据
    stats: {
      totalCount: 0,
      activeCount: 0,
      completedCount: 0,
      upcomingCount: 0
    },
    isLoggedIn: false, // 登录状态
  // 全局加载状态
  globalLoading: false,
  globalLoadingText: '用户信息加载中...',

  // 显示全局加载
  showGlobalLoading(text = '用户信息加载中...') {
    const app = getApp()
    app.showGlobalLoading({
      loadingText: text
    })
  },

  // 隐藏全局加载
  hideGlobalLoading() {
    const app = getApp()
    app.hideGlobalLoading()
  },

  // 更新全局加载状态
  updateGlobalLoading(data) {
    this.setData({
      globalLoading: data.globalLoading,
      globalLoadingText: data.globalLoadingText || this.data.globalLoadingText
    })
  },
    filterStatus: 'all', // all, active, completed, upcoming
    searchKeyword: '',
    // 评论相关数据
    showCommentModal: false,
    commentText: '',
    currentActivityId: '',
    currentActivityTitle: '',
    currentComments: [],
    isInputFocused: false
  },

  onLoad() {
    // 检查登录状态
    this.checkLoginStatus()
    this.loadMyActivities()
  },

  onShow() {
    // 每次显示页面时刷新数据
    console.log('页面显示，刷新活动数据')
    // 检查登录状态
    this.checkLoginStatus()
    this.loadMyActivities()
  },

  // 检查登录状态
  checkLoginStatus() {
    const isLoggedIn = auth.isLoggedIn()
    this.setData({ isLoggedIn })
    console.log('登录状态:', isLoggedIn)
  },

  // 加载我的活动数据
  async loadMyActivities() {
    this.setData({ loading: true })
    
    console.log('加载我的活动数据')
    
    try {
      // 获取用户信息
      const userInfo = auth.getCurrentUser()
      if (!userInfo || !userInfo.userId) {
        // 未登录时设置空数据，显示登录提示
        this.setData({ 
          loading: false,
          activities: [],
          allActivities: [],
          stats: {
            totalCount: 0,
            activeCount: 0,
            completedCount: 0,
            upcomingCount: 0
          }
        })
        return
      }

      // 调用API获取用户活动数据
      const response = await activities.getUserActivities({
        userId: userInfo.userId,
        page: 1,
        limit: 100 // 获取所有数据用于前端筛选
      })

      if (response.success) {
        const activitiesData = response.data.activities || []
        
        // 处理活动数据，转换为前端需要的格式
        const processedActivities = activitiesData.map(activity => {
          // 根据活动类型设置图标和主题
          const { icon, theme } = this.getActivityTheme(activity.title)
          
          return {
            id: activity.id,
            title: activity.title,
            subtitle: activity.subtitle || '',
            icon: icon,
            theme: theme,
            description: activity.content ? this.stripHtmlTags(activity.content) : '',
            startTime: this.formatActivityTime(activity.start_date, activity.start_time),
            endTime: this.formatActivityTime(activity.end_date, activity.end_time),
            status: activity.status,
            statusText: this.getStatusText(activity.status),
            joinTime: activity.registration_time ? activity.registration_time.split(' ')[0] : '',
            contact: activity.contact_person || '',
            phone: activity.contact_phone || '',
            participants: activity.current_participants || 0,
            maxParticipants: activity.max_participants || 0,
            participationStatus: activity.participation_status || '',
            images: activity.images || []
          }
        })

        // 计算统计数据
        const stats = {
          totalCount: processedActivities.length,
          activeCount: processedActivities.filter(item => item.status === 'active').length,
          completedCount: processedActivities.filter(item => item.status === 'completed').length,
          upcomingCount: processedActivities.filter(item => item.status === 'upcoming').length
        }

        this.setData({
          activities: processedActivities,
          allActivities: processedActivities, // 保存原始数据
          stats: stats,
          loading: false
        })

        console.log('活动数据加载成功:', processedActivities.length)
      } else {
        throw new Error(response.message || '获取活动数据失败')
      }
    } catch (error) {
      console.error('加载活动数据失败:', error)
      wx.showToast({
        title: error.message || '加载失败',
        icon: 'none'
      })
      
      // 设置空数据
      this.setData({
        activities: [],
        allActivities: [],
        stats: {
          totalCount: 0,
          activeCount: 0,
          completedCount: 0,
          upcomingCount: 0
        },
        loading: false
      })
    }
  },

  // 根据活动标题获取图标和主题
  getActivityTheme(title) {
    const titleLower = title.toLowerCase()
    
    if (titleLower.includes('春耕') || titleLower.includes('农业') || titleLower.includes('农机')) {
      return { icon: '🌱', theme: 'spring' }
    } else if (titleLower.includes('文化') || titleLower.includes('传统') || titleLower.includes('技艺')) {
      return { icon: '🎭', theme: 'culture' }
    } else if (titleLower.includes('丰收') || titleLower.includes('秋收') || titleLower.includes('农产品')) {
      return { icon: '🌾', theme: 'autumn' }
    } else if (titleLower.includes('防暑') || titleLower.includes('夏季') || titleLower.includes('清凉')) {
      return { icon: '☀️', theme: 'summer' }
    } else if (titleLower.includes('温暖') || titleLower.includes('冬季') || titleLower.includes('过冬')) {
      return { icon: '❄️', theme: 'winter' }
    } else {
      return { icon: '📅', theme: 'default' }
    }
  },

  // 获取状态文本
  getStatusText(status) {
    const statusMap = {
      'upcoming': '即将开始',
      'active': '进行中',
      'completed': '已结束',
      'cancelled': '已取消'
    }
    return statusMap[status] || '未知状态'
  },

  // 去除HTML标签
  stripHtmlTags(html) {
    if (!html) return ''
    return html.replace(/<[^>]*>/g, '').replace(/&nbsp;/g, ' ').trim()
  },

  // 筛选活动
  onFilterChange(e) {
    const status = e.currentTarget.dataset.status
    console.log('筛选状态:', status)
    this.setData({ filterStatus: status })
    this.filterActivities()
  },

  // 搜索活动
  onSearchInput(e) {
    const keyword = e.detail.value
    console.log('搜索关键词:', keyword)
    this.setData({ searchKeyword: keyword })
    this.filterActivities()
  },

  // 筛选和搜索活动
  filterActivities() {
    const { allActivities, filterStatus, searchKeyword } = this.data
    let filteredActivities = allActivities

    console.log('筛选前活动数量:', allActivities.length)
    console.log('筛选状态:', filterStatus)
    console.log('搜索关键词:', searchKeyword)

    // 按状态筛选
    if (filterStatus !== 'all') {
      filteredActivities = filteredActivities.filter(item => item.status === filterStatus)
      console.log('状态筛选后数量:', filteredActivities.length)
    }

    // 按关键词搜索
    if (searchKeyword && searchKeyword.trim()) {
      const keyword = searchKeyword.toLowerCase()
      filteredActivities = filteredActivities.filter(item => 
        item.title.toLowerCase().includes(keyword) ||
        item.description.toLowerCase().includes(keyword)
      )
      console.log('搜索筛选后数量:', filteredActivities.length)
    }

    console.log('最终筛选结果数量:', filteredActivities.length)
    this.setData({ activities: filteredActivities })
    
    // 如果没有搜索结果，显示提示
    if (filteredActivities.length === 0) {
      if (searchKeyword && searchKeyword.trim()) {
        wx.showToast({
          title: '未找到相关活动',
          icon: 'none',
          duration: 1500
        })
      }
    }
  },

  // 查看活动详情
  onViewActivityDetail(e) {
    const { id } = e.currentTarget.dataset
    console.log('查看活动详情:', id)
    wx.navigateTo({
      url: `/pages/activity/detail/index?id=${id}`,
      success: () => console.log('跳转到活动详情页面成功'),
      fail: (err) => {
        console.error('跳转失败:', err)
        wx.showToast({ title: '页面跳转失败', icon: 'none' })
      }
    })
  },

  // 取消参与活动
  onCancelActivity(e) {
    const { id, title } = e.currentTarget.dataset
    
    console.log('取消参与活动:', id, title)
    
    wx.showModal({
      title: '确认取消',
      content: `确定要取消参与"${title}"活动吗？`,
      confirmText: '确认取消',
      cancelText: '继续参与',
      confirmColor: '#ef4444',
      success: (res) => {
        if (res.confirm) {
          this.cancelActivity(id)
        }
      }
    })
  },

  // 执行取消参与
  async cancelActivity(id) {
    try {
      // 获取用户信息
      const userInfo = auth.getCurrentUser()
      if (!userInfo || !userInfo.userId) {
        wx.showToast({
          title: '请先登录',
          icon: 'none'
        })
                // 数据加载完成，隐藏全局加载
        this.hideGlobalLoading();
        return
      }

      // 调用API取消报名
      const response = await activities.cancelRegistration(id, {
        userId: userInfo.userId
      })

      if (response.success) {
        // 从原始活动列表中移除
        const allActivities = this.data.allActivities.filter(item => item.id != id)
        const activities = this.data.activities.filter(item => item.id != id)
        
        // 重新计算统计数据
        const stats = {
          totalCount: allActivities.length,
          activeCount: allActivities.filter(item => item.status === 'active').length,
          upcomingCount: allActivities.filter(item => item.status === 'upcoming').length,
          completedCount: allActivities.filter(item => item.status === 'completed').length
        }
        
        this.setData({ 
          allActivities, 
          activities, 
          stats 
        })
        
        wx.showToast({
          title: '已取消参与',
          icon: 'success'
        })
      } else {
        throw new Error(response.message || '取消参与失败')
      }
    } catch (error) {
      console.error('取消参与失败:', error)
      wx.showToast({
        title: error.message || '取消参与失败',
        icon: 'none'
      })
    }
  },

  // 联系负责人
  onContact(e) {
    const { contact, phone } = e.currentTarget.dataset
    
    wx.showActionSheet({
      itemList: [`联系${contact}`, '拨打电话'],
      success: (res) => {
        if (res.tapIndex === 0) {
          wx.showModal({
            title: '联系信息',
            content: `负责人：${contact}\n电话：${phone}`,
            showCancel: false,
            confirmText: '知道了'
          })
        } else if (res.tapIndex === 1) {
          wx.makePhoneCall({
            phoneNumber: phone,
            fail: () => {
              wx.showToast({ title: '拨号失败', icon: 'none' })
            }
          })
        }
      }
    })
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.loadMyActivities()
    
    setTimeout(() => {
      wx.stopPullDownRefresh()
    }, 1000)
  },

  // 分享活动
  onShareActivity(e) {
    const { id, title, description } = e.currentTarget.dataset
    
    return {
      title: title,
      desc: description,
      path: `/pages/activity/detail/index?id=${id}`
    }
  },

  // 去登录（未登录时跳转到登录页面）
  onGoToActivities() {
    wx.redirectTo({
      url: '/pages/auth/login/index',
      success: () => console.log('跳转到登录页面成功'),
      fail: (err) => {
        console.error('跳转失败:', err)
        wx.showToast({ title: '页面跳转失败', icon: 'none' })
      }
    })
  },

  // 处理活动参与状态更新
  updateActivityStatus(activityId, newStatus) {
    const { allActivities } = this.data
    const updatedActivities = allActivities.map(item => {
      if (item.id === activityId) {
        return { ...item, status: newStatus }
      }
      return item
    })
    
    this.setData({ allActivities: updatedActivities })
    this.filterActivities()
  },

  // 评论活动
  async onCommentActivity(e) {
    console.log('评论按钮被点击')
    const { id, title } = e.currentTarget.dataset
    console.log('活动ID:', id, '活动标题:', title)
    
    try {
      // 调用API获取活动评论
      const response = await activities.getActivityComments(id, {
        page: 1,
        limit: 50
      })

      let comments = []
      if (response.success && response.data.comments) {
        // 处理评论数据
        comments = response.data.comments.map(comment => ({
          id: comment.id,
          userName: comment.user_name || '匿名用户',
          content: comment.content,
          createTime: comment.created_at ? comment.created_at.split(' ')[0] + ' ' + comment.created_at.split(' ')[1].substring(0, 5) : '',
          likeCount: comment.like_count || 0
        }))
      }
      
      console.log('获取到的评论数据:', comments)
      
      this.setData({
        currentActivityId: id,
        currentActivityTitle: title,
        currentComments: comments,
        showCommentModal: true,
        commentText: ''
      })
      
      console.log('弹出层应该显示了，showCommentModal:', this.data.showCommentModal)
    } catch (error) {
      console.error('获取评论失败:', error)
      wx.showToast({
        title: '获取评论失败',
        icon: 'none'
      })
      
      // 设置空评论列表
      this.setData({
        currentActivityId: id,
        currentActivityTitle: title,
        currentComments: [],
        showCommentModal: true,
        commentText: ''
      })
    }
  },

  // 隐藏评论弹出层
  onHideCommentModal() {
    // 如果输入框正在聚焦，不关闭弹出层
    if (this.data.isInputFocused) {
      return
    }
    
    this.setData({
      showCommentModal: false,
      commentText: '',
      isInputFocused: false
    })
  },

  // 阻止事件冒泡
  stopPropagation() {
    // 空函数，用于阻止事件冒泡
  },

  // 评论输入
  onCommentInput(e) {
    const value = e.detail.value
    this.setData({ commentText: value })
  },

  // 输入框获得焦点
  onCommentInputFocus() {
    this.setData({ isInputFocused: true })
  },

  // 输入框失去焦点
  onCommentInputBlur() {
    // 延迟设置，避免点击发送按钮时弹出层关闭
    setTimeout(() => {
      this.setData({ isInputFocused: false })
    }, 200)
  },

  // 提交评论
  async onSubmitComment() {
    const { commentText, currentActivityId } = this.data
    
    if (!commentText || commentText.trim() === '') {
      wx.showToast({ title: '请输入评论内容', icon: 'none' })
      return
    }
    
    try {
      // 获取用户信息
      const userInfo = auth.getCurrentUser()
      if (!userInfo || !userInfo.userId) {
        wx.showToast({
          title: '请先登录',
          icon: 'none'
        })
        return
      }

      // 调用API提交评论
      const response = await activities.publishComment(currentActivityId, {
        userId: userInfo.userId,
        content: commentText.trim()
      })

      if (response.success) {
        // 创建新评论
        const newComment = {
          id: response.data.comment.id,
          userName: userInfo.name || userInfo.username || '我',
          content: commentText.trim(),
          createTime: this.formatTime(new Date()),
          likeCount: 0
        }
        
        // 添加到评论列表
        const currentComments = [...this.data.currentComments, newComment]
        
        this.setData({
          currentComments: currentComments,
          commentText: ''
        })
        
        wx.showToast({ 
          title: '评论成功！', 
          icon: 'success',
          duration: 1500
        })
      } else {
        throw new Error(response.message || '评论提交失败')
      }
    } catch (error) {
            this.hideGlobalLoading();
      console.error('评论提交失败:', error)
      wx.showToast({
        title: error.message || '评论提交失败',
        icon: 'none'
      })
    }
  },

  // 点赞评论
  onLikeComment(e) {
    const { id } = e.currentTarget.dataset
    const currentComments = this.data.currentComments.map(comment => {
      if (comment.id === id) {
        return { ...comment, likeCount: (comment.likeCount || 0) + 1 }
      }
      return comment
    })
    
    this.setData({ currentComments })
    
    wx.showToast({ 
      title: '点赞成功！', 
      icon: 'success',
      duration: 1000
    })
  },

  // 格式化活动时间显示（更友好的格式）
  formatActivityTime(dateStr, timeStr) {
    if (!dateStr) return ''
    
    try {
      // 处理各种可能的日期时间格式
      let fullDateTime = dateStr
      
      // 如果有单独的时间字符串，组合日期和时间
      if (timeStr) {
        // 如果时间包含T和Z，说明是ISO格式，需要提取时间部分
        if (timeStr.includes('T')) {
          timeStr = timeStr.split('T')[1].split('.')[0] // 提取HH:MM:SS部分
        }
        
        // 如果日期包含T，说明是ISO格式，需要提取日期部分
        if (dateStr.includes('T')) {
          dateStr = dateStr.split('T')[0] // 提取YYYY-MM-DD部分
        }
        
        fullDateTime = `${dateStr} ${timeStr}`
      }
      
      // 解析日期时间
      const date = new Date(fullDateTime)
      if (isNaN(date.getTime())) return dateStr
      
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      
      // 返回更友好的格式：YYYY年MM月DD日 HH:MM
      return `${year}年${month}月${day}日 ${hours}:${minutes}`
    } catch (error) {
      console.error('活动时间格式化错误:', error)
      return dateStr
    }
  },

  // 格式化时间
  formatTime(date) {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    
    return `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')} ${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`
  },


})
